package com.ruoyi.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.Message;
import com.ruoyi.common.core.domain.SendInfo;
import com.ruoyi.common.tio.StartTioRunner;
import com.ruoyi.common.tio.TioServerConfig;
import com.ruoyi.common.tio.WsOnlineContext;
import com.ruoyi.common.utils.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.Set;

import com.ruoyi.customer.domain.MessageRecord;
import com.ruoyi.customer.mapper.MessageRecordMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.server.ServerTioConfig;
import org.tio.websocket.common.WsResponse;

@RequiredArgsConstructor
@Component
@Slf4j
public class MessageSend {

    private final StartTioRunner startTioRunner;
    private final MessageRecordMapper messageRecordMapper;

    public void sendNotice(String type, String content, List<String> userIds, String operationName) {
        Set<String> wsRegisterUser = WsOnlineContext.getWSRegisterUser();
        wsRegisterUser.forEach(userId -> {
            if (StringUtils.isNotBlank(userId)) {
                MessageRecord messageRecord = new MessageRecord();
                messageRecord.setCreateBy(operationName);
                messageRecord.setType(type);
                // 公告 上线的人全发
                if (Objects.equals(Constants.MESSAGE_NOTICE, type) || Objects.equals(Constants.MESSAGE_STAR, type)) {
                    sentMessage(userId, type, content, messageRecord);
                }

                // 备忘录提醒、下推送、主管点评提醒
                if (Objects.equals(Constants.MESSAGE_PUSH, type)
                        || Objects.equals(Constants.MESSAGE_MEMO_RECORD, type)
                        || Objects.equals(Constants.MESSAGE_COMMENT_RECORD, type)
                        || Objects.equals(Constants.DIS_MESSAGE, type)
                        || Objects.equals(Constants.CHANNEL_PUSH_DIS_ADMIN, type)
                        || Objects.equals(Constants.CHANNEL_PUSH_DIS_BUS, type)) {

                    if (userIds.contains(userId)) {
                        sentMessage(userId, type, content, messageRecord);
                    }
                }
            }
        });
    }

    private void sentMessage(String userId, String type, String content, MessageRecord messageRecord) {
        ServerTioConfig serverTioConfig = startTioRunner.getAppStarter().getWsServerStarter()
                .getServerTioConfig();
        ChannelContext cc = WsOnlineContext.getChannelContextByUser(userId);
        if (cc != null && !cc.isClosed) {
            SendInfo sendInfo = new SendInfo();
            sendInfo.setCode(Constants.MSG_MESSAGE);
            Message msg = new Message();
            msg.setContent(content);
            msg.setTimestamp(System.currentTimeMillis());
            msg.setType(type);
            sendInfo.setMessage(msg);
            WsResponse wsResponse = null;
            try {
                wsResponse = WsResponse.fromText(new ObjectMapper().writeValueAsString(sendInfo),
                        TioServerConfig.CHARSET);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                log.error("消息发送：内容为----{}  报错信息：{}", type + "----" + content, e.getMessage());
            }
            Tio.sendToUser(serverTioConfig, userId, wsResponse);
            messageRecord.setUserIds(userId);
            messageRecord.setContext(content);
            messageRecordMapper.insert(messageRecord);
        }
    }
}
